package com.dlc.shop.coupon.common.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.event.PopupCouponInfoEvent;
import com.dlc.shop.coupon.common.model.Coupon;
import com.dlc.shop.coupon.common.model.CouponUser;
import com.dlc.shop.coupon.common.service.CouponService;
import com.dlc.shop.coupon.common.service.CouponUserService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author TRACK
 */
@Component("popupCouponInfoListener")
@AllArgsConstructor
public class PopupCouponInfoListener {

    private final CouponService couponService;
    private final CouponUserService couponUserService;

    @EventListener(PopupCouponInfoEvent.class)
    public void esProductCouponInfoListener(PopupCouponInfoEvent event){
        if (Objects.nonNull(event.getUserId())) {
            // 获取领券数
            long receiveCount = couponUserService.count(new LambdaQueryWrapper<CouponUser>().eq(CouponUser::getCouponId, event.getCouponId())
                    .eq(CouponUser::getUserId, event.getUserId()));
            event.setReceiveCount(receiveCount);
        }
        // 获取库存
        Coupon coupon = couponService.getById(event.getCouponId());
        event.setStock(coupon.getStocks());
        event.setStatus(coupon.getPutonStatus());
    }
}
